package com.yuandian.utils;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.List;

/**
 * 说明：pdf工具类
 * @Author yanjun
 * @Date 2021/4/26 9:53
 */
@Component
public class PdfUtil {

    private static String basePath = "d:/";



    public static String generalPdf(String fileName, String[] headers, List<Object[]> dataList) {
        File basePathFile = new File(basePath);
        if (!basePathFile.exists()) {
            basePathFile.mkdirs();
        }
        String filePath = basePath + fileName;
        Document document = new Document();
        try {
            PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(filePath));
            document.open();

            // 设置水印
            PdfContentByte waterMar = pdfWriter.getDirectContentUnder();
            waterMar.beginText();
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.1f);
            try {
                URL url =Thread.currentThread().getContextClassLoader().getResource("conf/images/water-mar.png");
                final Image image=Image.getInstance(url);
                image.setAbsolutePosition(-200, 0);
                image.setRotation(30);
                image.setRotationDegrees(45);
                image.scalePercent(90);
                waterMar.setGState(gs);
                waterMar.addImage(image);
                waterMar.endText();
                waterMar.stroke();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                waterMar = null;
                gs = null;
            }

            PdfPTable table = new PdfPTable(1);
            table.setKeepTogether(true);
            table.setSplitLate(false);

            // 标题
            PdfPTable table1 = new PdfPTable(1);
            Paragraph p = buildParagraph("业务详单列表", 12f, BaseColor.BLACK);
            p.setAlignment(1);
            p.setSpacingBefore(15f);
            PdfPCell cell0 = new PdfPCell();
            cell0.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            cell0.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell0.setPadding(-2f);
            cell0.setPaddingBottom(8f);
            cell0.addElement(p);
            cell0.setBorder(0);
            table1.addCell(cell0);

            // 表格
            // 表头
            int columnLen = headers.length;
            PdfPTable table2 = new PdfPTable(columnLen);
            for (String header : headers) {
                PdfPCell cell = new PdfPCell();
                Paragraph pp = buildParagraph(header, 6f, BaseColor.BLACK);
                pp.setAlignment(1);
                cell.addElement(pp);
                table2.addCell(cell);
            }
            // 表数据
            dataList.forEach(datas -> {
                for (Object data : datas) {
                    PdfPCell cell = new PdfPCell();
                    Paragraph pp = buildParagraph(String.valueOf(data), 6f, BaseColor.BLACK);
                    pp.setAlignment(1);
                    cell.addElement(pp);
                    table2.addCell(cell);
                }
            });

            PdfPCell c1 = new PdfPCell();
            c1.setBorder(0);
            c1.addElement(table1);

            PdfPCell c2 = new PdfPCell();
            c2.setBorder(0);
            c2.addElement(table2);

            table.addCell(c1);
            table.addCell(c2);

            document.add(table);
            document.close();
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        }
        return "/temp/" + fileName;
    }

    /**
     * 导出pdf
     * @param fileName 文件名
     * @param dpslFlieExportRoute 系统配置的路径
     * @param title 标题
     * @param headers 列名
     * @param dataList 表数据
     * @return
     */
    public static String customDownPDF(String fileName,String dpslFlieExportRoute, String title, String[] headers, List<Object[]> dataList) {
        File basePathFile = new File(dpslFlieExportRoute);
        if (!basePathFile.exists()) {
            basePathFile.mkdirs();
        }
        String filePath = dpslFlieExportRoute + "/"  + fileName;
        Document document = new Document(PageSize.A4, 1, 1, 20, 20);
        try {
            PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(filePath));

            // 设置水印
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.1f);
            try {
//                int inx = this.basePath.indexOf("temp");
//                final Image image = Image.getInstance(this.basePath.substring(0, inx) + "/images/water-mar.png");
                URL url =Thread.currentThread().getContextClassLoader().getResource("conf/images/water-mar.png");

                final Image image=Image.getInstance(url);
                image.setAbsolutePosition(-200, 0);
                image.setRotation(30);
                image.setRotationDegrees(45);
                image.scalePercent(90);
                pdfWriter.setPageEvent(new PdfPageEvent() {
                    @Override
                    public void onStartPage(PdfWriter writer, Document doc) {
                        PdfContentByte wm = writer.getDirectContentUnder();
                        wm.beginText();
                        wm.setGState(gs);
                        try {
                            wm.addImage(image);
                        } catch (DocumentException e) {
                            e.printStackTrace();
                        }
                        wm.endText();
                        wm.stroke();
                    }

                    @Override
                    public void onSectionEnd(PdfWriter arg0, Document arg1, float arg2) {}
                    @Override
                    public void onSection(PdfWriter arg0, Document arg1, float arg2, int arg3, Paragraph arg4) {}
                    @Override
                    public void onParagraphEnd(PdfWriter arg0, Document arg1, float arg2) {}
                    @Override
                    public void onParagraph(PdfWriter arg0, Document arg1, float arg2) {}
                    @Override
                    public void onOpenDocument(PdfWriter arg0, Document arg1) {}
                    @Override
                    public void onGenericTag(PdfWriter arg0, Document arg1, Rectangle arg2, String arg3) {}
                    @Override
                    public void onEndPage(PdfWriter arg0, Document arg1) {}
                    @Override
                    public void onCloseDocument(PdfWriter arg0, Document arg1) {}
                    @Override
                    public void onChapterEnd(PdfWriter arg0, Document arg1, float arg2) {}
                    @Override
                    public void onChapter(PdfWriter arg0, Document arg1, float arg2, Paragraph arg3) {}
                });
            } catch (IOException e) {
                e.printStackTrace();
            }

            document.open();

            PdfPTable table = new PdfPTable(1);
            table.setKeepTogether(true);
            table.setSplitLate(false);

            // 标题
            PdfPTable table1 = new PdfPTable(1);
            table1.setWidthPercentage(110);
            Paragraph p = buildParagraph(title, 12f, BaseColor.BLACK);
            p.setAlignment(1);
            p.setSpacingBefore(15f);
            PdfPCell cell0 = new PdfPCell();
            cell0.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            cell0.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell0.setPadding(-2f);
            cell0.setPaddingBottom(8f);
            cell0.addElement(p);
            cell0.setBorder(0);
            table1.addCell(cell0);

            // 表格
            // 表头
            int columnLen = headers.length;
            PdfPTable table2 = new PdfPTable(columnLen);
            table2.setWidthPercentage(110);
            for (String header : headers) {
                PdfPCell cell = new PdfPCell();
                Paragraph pp = buildParagraph(header, 6f, BaseColor.BLACK);
                pp.setAlignment(1);
                cell.addElement(pp);
                table2.addCell(cell);
            }
            // 表数据
            dataList.forEach(datas -> {
                for (Object data : datas) {
                    PdfPCell cell = new PdfPCell();
                    Paragraph pp = buildParagraph(String.valueOf(data), 6f, BaseColor.BLACK);
                    pp.setAlignment(1);
                    cell.addElement(pp);
                    table2.addCell(cell);
                }
            });

            PdfPCell c1 = new PdfPCell();
            c1.setBorder(0);
            c1.addElement(table1);

            PdfPCell c2 = new PdfPCell();
            c2.setBorder(0);
            c2.addElement(table2);

            table.addCell(c1);
            table.addCell(c2);

            document.add(table);
            document.close();
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        }
        return filePath;
    }



    private static Paragraph buildParagraph(String content, float size, BaseColor color) {
        Paragraph res = new Paragraph();
        FontSelector selector = new FontSelector();
        Font f1 = FontFactory.getFont(FontFactory.TIMES_ROMAN, size);
        f1.setColor(color);
        Font f2 = FontFactory.getFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED, size);
        f2.setColor(color);
        selector.addFont(f1);
        selector.addFont(f2);
        Phrase ph = selector.process(content);
        res.add(ph);
        return res;
    }
}
